import React from "react";
import { View } from "react-native";
import { Card, Button, FormLabel, FormInput } from "react-native-elements";
import Toast from 'react-native-root-toast';
import { onLogin, login } from "../auth";

class Login extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      username: "",
      password: ""
    }
  }

  doLogin() {
      login(this.state).then((response) => {
        if (response.ret == 0) {
          onLogin(response.data).then(() => {
            this.props.navigation.navigate("Authenticated");
          })
          
        } else {
          Toast.show(response.msg);
        }
      }).catch((error) => {
        Toast.show(error.message);
      })
  }

  goToRegister() {
    this.props.navigation.navigate("Register");
  }

  render() {
    return (
      <View style={{ paddingVertical: 20 }}>
      <Card>
        <FormLabel>Email</FormLabel>
        <FormInput placeholder="邮箱" onChangeText={(username) => this.setState({username})} />
        <FormLabel>Password</FormLabel>
        <FormInput secureTextEntry placeholder="密码" onChangeText={(password) => this.setState({password})} />

        <Button
          buttonStyle={{ marginTop: 20 }}
          backgroundColor="#03A9F4"
          title="登录"
          onPress={this.doLogin.bind(this)}
        />
        <Button
          buttonStyle={{ marginTop: 20 }}
          backgroundColor="transparent"
          textStyle={{ color: "#bcbec1" }}
          title="注册"
          onPress={this.goToRegister.bind(this)}
        />
      </Card>
    </View>
    )
  }
  
}

module.exports = Login;